package com.icinfo.cloud.provider.punish.common.csourcedocumentoperate.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.*;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.*;
import com.icinfo.cloud.provider.punish.approval.vo.LineTerritoryInfoVo;
import com.icinfo.cloud.provider.punish.common.csourcedocumentoperate.dto.CSourceDocCommonHtmlRequest;
import com.icinfo.cloud.provider.punish.common.csourcedocumentoperate.dto.CSourceDocCommonOperateSaveDto;
import com.icinfo.cloud.provider.punish.common.csourcedocumentoperate.mapper.CSourceDocCommonOperateMapper;
import com.icinfo.cloud.provider.punish.common.csourcedocumentoperate.service.ICSourceDocCommonOperateService;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.FillAndConvertToPdfRequest;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.StageDocCommonOperateSaveDto;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentRecordStatusEnum;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentStatusEnum;
import com.icinfo.cloud.provider.punish.common.documentoperate.vo.DocumentCommonFormDataVo;
import com.icinfo.cloud.provider.punish.common.documentoperate.vo.DocumentCommonFormHtmlVo;
import com.icinfo.cloud.provider.punish.common.nonlitigation.dto.CaseNonLitigationExecuteRequestDto;
import com.icinfo.cloud.provider.punish.common.nonlitigation.service.ICaseNonLitigationExecuteRecordService;
import com.icinfo.cloud.provider.punish.common.seal.dto.FileSealInfoQueryDto;
import com.icinfo.cloud.provider.punish.common.seal.service.IFileSealProvinceUnifiedService;
import com.icinfo.cloud.provider.punish.config.mapper.ConfigBusiParamDocumentColumnMapper;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentColumn;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;
import com.icinfo.cloud.provider.punish.config.service.IConfigBusiParamDeptService;
import com.icinfo.cloud.provider.punish.config.service.IConfigBusiParamDocumentInfoService;
import com.icinfo.cloud.provider.punish.config.service.ISysDepartParamService;
import com.icinfo.cloud.provider.punish.config.vo.BusiTableOperateVo;
import com.icinfo.cloud.provider.punish.csource.manage.enums.CaseSourceOperateTypeEnum;
import com.icinfo.cloud.provider.punish.csource.manage.enums.CaseSourceStatusEnum;
import com.icinfo.cloud.provider.punish.csource.manage.mapper.CaseSourceDocumentRecordHisMapper;
import com.icinfo.cloud.provider.punish.csource.manage.mapper.CaseSourceDocumentRecordMapper;
import com.icinfo.cloud.provider.punish.csource.manage.mapper.CaseSourceRegisterMainInfoMapper;
import com.icinfo.cloud.provider.punish.csource.manage.model.CaseSourceDocumentRecord;
import com.icinfo.cloud.provider.punish.csource.manage.model.CaseSourceDocumentRecordHis;
import com.icinfo.cloud.provider.punish.csource.manage.model.CaseSourceHandlePersonRecord;
import com.icinfo.cloud.provider.punish.csource.manage.model.CaseSourceRegisterMainInfo;
import com.icinfo.cloud.provider.punish.csource.manage.service.ICaseSourceDocumentRecordService;
import com.icinfo.cloud.provider.punish.csource.manage.service.ICaseSourceHandlePersonRecordService;
import com.icinfo.cloud.provider.punish.csource.manage.service.ICaseSourcePartyInfoService;
import com.icinfo.cloud.provider.punish.csource.manage.vo.CaseSourcePartyInfoVo;
import com.icinfo.cloud.provider.punish.evideinv.service.EvidenceInventoryService;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.HandlePersonTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseMainDetailSimpleInfoMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseTemporaryRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseDocumentNumberSerialService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseMainDetailSimpleInfoService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseMainInfoStatusChangeRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseTemporaryRecordService;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.enums.CaseStatusChangeTypeEnum;
import com.icinfo.cloud.workflow.config.service.IConfigWorkFlowDocumentService;
import com.icinfo.cloud.workflow.work.service.IWorkFlowRollSubMainInfoService;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.tools.utils.DateUtils;
import com.icinfo.framework.tools.utils.HttpClientUtil;
import com.icinfo.framework.tools.utils.MapUtils;
import com.icinfo.framework.tools.utils.StringUtils;
import com.timevale.tgtext.text.pdf.PdfReader;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 描述：文书阶段公共操作接口事先类
 *
 * @author xiangyuyu
 * @date 2022/2/16 21:07
 */
@Service
@Slf4j
public class CSourceDocCommonOperateServiceImpl implements ICSourceDocCommonOperateService {
    @Value("${document.url}")
    private String url;
    @Value("${document.api.templateDetail}")
    private String templateDetail;
    @Value("${document.api.uploadConvertedPdf}")
    private String uploadConvertedPdf;
    @Value("${document.api.uploadBase64File}")
    private String uploadBase64File;
    @Resource
    IConfigBusiParamDocumentInfoService configBusiParamDocumentInfoService;
    @Autowired
    private ICaseSourceHandlePersonRecordService caseSourceHandlePersonRecordService;
    @Autowired
    private IConfigBusiParamDeptService configBusiParamDeptService;
    @Resource
    private CSourceDocCommonOperateMapper cSourceDocCommonOperateMapper;
    @Resource
    private IFileSealProvinceUnifiedService fileSealProvinceUnifiedService;

    @Autowired
    private ICaseDocumentNumberSerialService caseDocumentNumberSerialService;
    @Resource
    ICaseTemporaryRecordService caseTemporaryRecordService;

    @Autowired
    private CaseSourceDocumentRecordMapper caseSourceDocumentRecordMapper;
    @Autowired
    private ConfigBusiParamDocumentColumnMapper configBusiParamDocumentColumnMapper;
    @Autowired
    @Resource
    private ICaseSourceDocumentRecordService caseSourceDocumentRecordService;
    @Autowired
    private CaseSourceDocumentRecordHisMapper caseSourceDocumentRecordHisMapper;
    @Autowired
    private ICaseSourcePartyInfoService caseSourcePartyInfoService;
    @Autowired
    private ISysDepartParamService sysDepartParamService;
    @Resource
    private ICaseNonLitigationExecuteRecordService caseNonLitigationExecuteRecordService;
    @Resource
    private EvidenceInventoryService evidenceInventoryService;
    @Resource
    private ICaseMainInfoStatusChangeRecordService caseMainInfoStatusChangeRecordService;

    @Resource
    private ICaseMainDetailSimpleInfoService caseMainDetailSimpleInfoService;
    @Autowired
    private IWorkFlowRollSubMainInfoService workFlowRollSubMainInfoService;
    @Resource
    private CaseMainDetailSimpleInfoMapper caseMainDetailSimpleInfoMapper;
    /**
     * 送达关联且需要当事人id的文书种类编码列表
     */
    public static List<String> sentRelatedNeedPartyIdDocumentKindCodeList;

    @Autowired
    private IConfigWorkFlowDocumentService configWorkFlowDocumentService;
    @Autowired
    private CaseSourceRegisterMainInfoMapper caseSourceRegisterMainInfoMapper;

    static {
        sentRelatedNeedPartyIdDocumentKindCodeList = new ArrayList<>();
        sentRelatedNeedPartyIdDocumentKindCodeList.add(Constant.STRING_KIND_CODE_SDHZ);
        sentRelatedNeedPartyIdDocumentKindCodeList.add(Constant.STRING_KIND_CODE_ZXQKHCJL);
        sentRelatedNeedPartyIdDocumentKindCodeList.add(Constant.STRING_KIND_CODE_XWTZS);
        sentRelatedNeedPartyIdDocumentKindCodeList.add(Constant.STRING_KIND_CODE_SQWTS);
        sentRelatedNeedPartyIdDocumentKindCodeList.add(Constant.STRING_KIND_CODE_SDDZQRS);
        sentRelatedNeedPartyIdDocumentKindCodeList.add(Constant.STRING_KIND_CODE_ZLGZTZS);
        sentRelatedNeedPartyIdDocumentKindCodeList.add(Constant.STRING_KIND_CODE_ZLTZWFXWJDS);
    }
    /**
     * 保存文书信息通用接口
     *
     * @param saveDto
     * @return {@link boolean}
     * @author liyafeng
     * @date 2022/2/27
     */
    @Override
    @Transactional(rollbackFor = {Error.class, Exception.class})
    public Map<String, Object> saveDocInfo(CSourceDocCommonOperateSaveDto saveDto) {
        CaseSourceRegisterMainInfo caseSourceRegisterMainInfo=caseSourceRegisterMainInfoMapper.selectByPrimaryKey(saveDto.getCaseSourceId());
        //String caseId = saveDto.getCaseId();
        //CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);

        //String handleType = caseMainInfo.getHandleType();
        //String casePartiesReasonType = caseMainInfo.getCasePartiesReasonType();
        String documentCatalogCode = saveDto.getDocumentCatalogCode();
        String partyId = saveDto.getPartyId();
        //查询文书配置信息
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(saveDto.getDocumentCatalogCode());
        String documentKindCode = configBusiParamDocumentInfo.getDocumentKindCode();
        saveDto.setDocumentKindCode(documentKindCode);
        //处理特殊文书
        //dealSpecialDocument(saveDto);

        //CaseMainInfoVo caseMainInfoVo = new CaseMainInfoVo();
        //BeanUtils.copyProperties(caseMainInfo, caseMainInfoVo);
        //获取案件信息
        /*if (caseMainInfoService.validateCaseIsInNotDealStatus(caseMainInfoVo, null)
                && !caseMainInfoService.validateIsTerminateCaseWhenBreakOff(caseMainInfoVo, null, documentKindCode)) {
            //如果存在行政处罚撤销决定书，可以送达
            CaseDocumentRecordDto documentInfo = caseDocumentRecordService.getCaseDocumentRecordByKindCode(caseId,Constant.STRING_KIND_CODE_XZCFCXJDS);
            if(ObjectUtils.isEmpty(documentInfo)){
                throw new BusinessException("当前案件状态不允许进行该操作");
            }
        }*/
        //String isShowPartiesSelector = caseMainInfoService.validateIsShowPartiesSelector(caseMainInfoVo, null);
        /*if (ObjectUtils.isEmpty(partyId)) {
            String caseFlowCode = caseMainInfo.getCaseFlowCode();
            String caseFlowVersion = caseMainInfo.getCaseFlowVersion();
            if(ObjectUtils.isEmpty(caseFlowCode)){
                caseFlowCode = "-";
            }
            if(ObjectUtils.isEmpty(caseFlowVersion)){
                caseFlowVersion = "-";
            }
            List<ConfigWorkFlowDocument> configWorkFlowDocumentList = configWorkFlowDocumentService.getConfigWorkFlowDocumentByWorkFLowAndCatalogCode(caseFlowCode,caseFlowVersion,caseMainInfo.getCaseCurrentLinkCode(),documentCatalogCode);
            if(configWorkFlowDocumentList.size()>0){
                if(Constant.STRING_2.equals(configWorkFlowDocumentList.get(0).getRelatedHolderType())
                        && HandleTypeEnum.PART_PUNISH.getCode().equals(handleType)){
                    throw new BusinessException("多当事人分别处罚时请指定当事人id");
                }
                *//*if (YesOrNoEnum.YES.getCode().equals(isShowPartiesSelector) &&
                        !CaseStatusChangeTypeEnum.isCaseChangeDocEnum(documentKindCode)) {
                    throw new BusinessException("多当事人分别处罚时请指定当事人id");
                }
                //多当事人，填写时例外 fixme:后期文书目录编码判断可优化成从数据库读取
                if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(casePartiesReasonType)
                        && "SDDZQRS6486A".equals(documentCatalogCode)) {
                    throw new BusinessException("多当事人时请指定当事人id");
                }*//*
                Map<String, String> map = casePartiesRecordService.getCasePartyIdNameInfo(caseId);
                partyId = map.get("partyId");
            } else if(CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseMainInfo.getCaseType())){
                Map<String, String> map = casePartiesRecordService.getCasePartyIdNameInfo(caseId);
                partyId = map.get("partyId");
            }
        }*/


        /*Map<String, Object> resultMap = new HashMap<>();
        if (Constant.STRING_2.equals(handleType)) {
            resultMap.put("workSubId", saveDto.getPartyId());
        }
        //重新赋值
        saveDto.setPartyId(partyId);*/
        Map<String, Object> resultMap = new HashMap<>();
        int num = 0;
        String documentId = "";
        resultMap.put("success", "true");
        //处理参数
        Map<String, Object> paramMap = dealDocParamMap(saveDto);
        long start = System.currentTimeMillis();
        System.out.println("文书生成开始----------------------------------" + start);
        //文号生成;1.判断文号是否已生成 2.未生成则 判断文号生成配置，审批前生成在此处生成，审批后生成在审批完成后生成
        //外部系统对接时使用对应系统文号
        String documentNumber="";
        /*String caseOrgCode = caseMainInfo.getCaseOrgCode();
        Object dataSource = saveDto.getDataMap().get("DATA_SOURCE");*/
        /*if (DocumentKindEnum.DOC_KIND_JYCXCFJDS.getCode().equals(documentKindCode)
                && !ObjectUtils.isEmpty(dataSource) && ApiVisitDataSourceEnum.isOutSystem((String) dataSource)) {
            //获取外部系统文号
            XfjdzfDocumentNumberInfoDto dto = new XfjdzfDocumentNumberInfoDto(caseOrgCode, DocumentKindEnum.DOC_KIND_JYCXCFJDS.getCode());
            documentNumber = xfjdzfInterfaceService.getDocumentNumber(dto);
        } else {
            documentNumber = genDocumentNumber(documentCatalogCode, saveDto, configBusiParamDocumentInfo);
        }*/

        // 案源登记表的文号特殊处理，指派时生成文号
        if (DocumentKindEnum.DOC_KIND_DK1AJLYDJB.getCode().equals(documentKindCode)){
            //案源登记修改时不需要重新生成文号
            if (CaseSourceOperateTypeEnum.MODIFY.getCode().equals(saveDto.getCaseSourceOperateType())){
                documentNumber= saveDto.getOriginDocumentNumber();
                paramMap.put("documentNumber",documentNumber);
            }else {
                if (CaseSourceStatusEnum.PRE_SURVEY.getIndex().equals(caseSourceRegisterMainInfo.getCaseSourceStatus()) ){
                    documentNumber = genDocumentNumber(documentCatalogCode, saveDto, configBusiParamDocumentInfo);
                    paramMap.put("documentNumber", documentNumber);
                }
            }
        }else {
            documentNumber = genDocumentNumber(documentCatalogCode, saveDto, configBusiParamDocumentInfo);
            paramMap.put("documentNumber", documentNumber);
        }


        //简易程序处罚决定书文号更新至简易案件详情表
       /* if (!ObjectUtils.isEmpty(documentNumber) && DocumentKindEnum.DOC_KIND_JYCXCFJDS.getCode().equals(documentKindCode)) {
            CaseMainDetailSimpleInfo caseMainDetailSimpleInfo = caseMainDetailSimpleInfoService.getCaseMainDetailSimpleInfo(caseId);
            caseMainDetailSimpleInfo.setPunishDocumentNumber(documentNumber);
            caseMainDetailSimpleInfoMapper.updateByPrimaryKeySelective(caseMainDetailSimpleInfo);
        }*/

        //计算送达期限
       /* String isSend = configBusiParamDocumentInfo.getIsSend();
        LocalDate sentDeadLine = null;
        if (YesOrNoEnum.YES.getCode().equals(isSend)) {
            Integer limitDay = configBusiParamDocumentInfo.getSendLimitDay();
            String limitDayType = configBusiParamDocumentInfo.getSendLimitType();
            sentDeadLine = caseDocumentRecordService.calculateSentDeadLine(caseId, documentCatalogCode, limitDay, limitDayType, false);
            if (ObjectUtils.isEmpty(sentDeadLine)) {
                throw new BusinessException("未获取到文书送达期限-caseId:" + caseId + ",documentCatalogCode:" + documentCatalogCode);
            }
        }*/

        //新增: 简易程序处罚决定书处理逻辑： 自行缴纳的，生成支付二维码；当场收缴的不生成支付二维码
        //处罚决定书时获取缴费二维码
       /* if (Constant.STRING_KIND_CODE_CFJDS.equals(configBusiParamDocumentInfo.getDocumentKindCode())
                || DocumentKindEnum.DOC_KIND_JYCXCFJDS.getCode().equals(configBusiParamDocumentInfo.getDocumentKindCode())) {
            boolean isCreate = true;
            String caseType = caseMainInfo.getCaseType();
            if (CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseType)) {
                //简易处罚,查询缴款方式
                CaseMainDetailSimpleInfo simpleInfo = caseMainDetailSimpleInfoService.getCaseMainDetailSimpleInfo(caseId);
                if (ObjectUtils.isEmpty(simpleInfo) || PayWayEnum.ON_SITE.getCode().equals(simpleInfo.getPayWay())) {
                    //当场收缴的不生成支付二维码
                    isCreate = false;
                }
            }

            if (isCreate) {
                //生成缴款单信息
                String paymentSlipNumber = iCasePaymentMainRecordService.saveCasePaymentMainRecord(caseId, documentCatalogCode, partyId, caseType);
                System.out.println("生成缴款单信息耗时------------------------" + (System.currentTimeMillis() - start));
                if (!ObjectUtils.isEmpty(paymentSlipNumber)) {
                    //获取缴款单二维码信息等
                    Map<String, String> paymentInfo = iPunishDecideService.getPaymentInfo(paymentSlipNumber);
                    System.out.println("获取缴款单二维码信息等耗时------------------------" + (System.currentTimeMillis() - start));
                    paramMap.put("qrBase64", paymentInfo.get("qrBase64"));
                    paramMap.put("XZCFJDS_JKDH", paymentSlipNumber);
                }
            }

        }*/
        // 处理案件操作变更
        //根据条件添加签章时间
        if ("1".equals(configBusiParamDocumentInfo.getIsDeptSign())) {
            if (("CLOSE-TRIGGER-APPROVAL-PASS".equals(saveDto.getCloseSignal()) && "1".equals(configBusiParamDocumentInfo.getIsApprove())) || !"1".equals(configBusiParamDocumentInfo.getIsApprove())) {
                paramMap.put("sealDate", DateUtils.formatDate(new Date(), "yyyy年M月d日"));
            }
        }
        //案件操作变更
        /*if (("CLOSE-TRIGGER-APPROVAL-PASS".equals(saveDto.getCloseSignal()) && "1".equals(configBusiParamDocumentInfo.getIsApprove())) || !"1".equals(configBusiParamDocumentInfo.getIsApprove())) {
            if (CaseStatusChangeTypeEnum.isCaseChangeDocEnum(documentKindCode)) {
                CaseStatusUpdateAfterApprovalDto approvalDto = new CaseStatusUpdateAfterApprovalDto();
                approvalDto.setCaseId(saveDto.getCaseId());
                approvalDto.setDocumentKindCode(documentKindCode);
                approvalDto.setCaseOperateType(CaseStatusChangeTypeEnum.getEnumByDocumentKindCode(documentKindCode).getCode());
                caseMainInfoStatusChangeRecordService.updateCaseStatusAfterLastApproval(approvalDto);
                // 处理延期时长
                if (CaseStatusChangeTypeEnum.POSTPONE.getDocumentKindCode().equals(documentKindCode)) {
                    Integer casePostponeDay = Integer.valueOf(saveDto.getDataMap().get(Constant.CASE_POSTPONE_DAY).toString());
                    LocalDateTime postponeDate = caseMainInfo.getCaseTimelimit().plusDays(casePostponeDay);
                    String postponeLimitDate = postponeDate.toLocalDate().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"));
                    paramMap.put("postponeLimitDate", postponeLimitDate);
                }
            }
        }*/
        //根据文书目录编码获取模板code
        String templateCode = getTemplateCodeByDocumentCatalogCode(saveDto.getDocumentCatalogCode(), saveDto.getCaseSourceId(), saveDto.getDataMap());
        //生成未签章文书
        FillAndConvertToPdfRequest pdfRequest = new FillAndConvertToPdfRequest();
        pdfRequest.setTemplateCode(templateCode);
        pdfRequest.setParamMap(saveDto.getDataMap());
        //判断文书模板类型是否为窄幅
        if (DocumentTemplateTypeEnum.NARROW_TEMPLATE.getCode().equals(saveDto.getDocumentTemplateType())) {
            pdfRequest.setTemplateType(DocumentTemplateKindEnum.NARROW_TEMPLATE.getCode());
        }
        //简易处罚决定书设置模板类型为窄幅
        if (DocumentKindEnum.DOC_KIND_JYCXCFJDS.getCode().equals(documentKindCode)) {
            pdfRequest.setTemplateType(DocumentTemplateKindEnum.NARROW_TEMPLATE.getCode());
        }
        Map<String, String> pdfUrl = getConvertedPdfUrl(pdfRequest);
        System.out.println("生成未签章文书耗时------------------------" + (System.currentTimeMillis() - start));
        if (ObjectUtil.isEmpty(pdfUrl)) {
            resultMap.put("success", "false");
            resultMap.put("msg", "文书生成失败！");
            return resultMap;
        }
        //判断是否需要签章
        String pdfSealUrl = "";
        String isGetBlankDoc = saveDto.getIsGetBlankDoc();
        String noSealPdfUrl = pdfUrl.get("fileUrl");
        if ("1".equals(configBusiParamDocumentInfo.getIsDeptSign()) && !YesOrNoEnum.YES.getCode().equals(isGetBlankDoc)) {
            //文书签章 1.非审批文书签章 2.审批通过文书签章
            if (("CLOSE-TRIGGER-APPROVAL-PASS".equals(saveDto.getCloseSignal()) && "1".equals(configBusiParamDocumentInfo.getIsApprove())) || !"1".equals(configBusiParamDocumentInfo.getIsApprove())) {
                FileSealInfoQueryDto queryDto = new FileSealInfoQueryDto();
                queryDto.setFileBase64(pdfUrl.get("fileBase64"));
                pdfSealUrl = dealFileSeal(queryDto);
                if (log.isDebugEnabled()){
                    log.debug("签章耗时------------------------" + (System.currentTimeMillis() - start));
                }
                if (StringUtils.isBlank(pdfSealUrl)) {
                    resultMap.put("success", "false");
                    resultMap.put("msg", "文书签章失败！");
                    return resultMap;
                }
                Map<String, Object> operateMap = operateCaseDocumentRecord(saveDto.getDocumentCatalogCode(), caseSourceRegisterMainInfo, pdfUrl.get("fileUrl"), documentNumber, paramMap, pdfSealUrl, saveDto.getIsMultipleDoc(), saveDto.getBelongDocumentId(), partyId, saveDto.getDocumentTemplateType());
                num = MapUtils.getIntValue(operateMap, "num", 0);
                documentId = MapUtils.getString(operateMap, "documentId", "");
            }
            if (!"CLOSE-TRIGGER-APPROVAL-PASS".equals(saveDto.getCloseSignal()) && "1".equals(configBusiParamDocumentInfo.getIsApprove())) {
                //num = operateCaseDocumentRecord(saveDto.getDocumentCatalogCode(), caseMainInfo, pdfUrl.get("fileUrl"), documentNumber, paramMap, pdfSealUrl, sentDeadLine);

                //从签字捺印过来，原先签章文件是非空的，要保留
                CaseSourceDocumentRecord oriRecord = caseSourceDocumentRecordService.getCaseDocumentRecord(saveDto.getCaseSourceId(), documentCatalogCode, partyId);
                if (!ObjectUtils.isEmpty(oriRecord) && !ObjectUtils.isEmpty(oriRecord.getDocumentUrlAfterSeal())) {
                    pdfSealUrl = oriRecord.getDocumentUrlAfterSeal();
                }
                //num = operateCaseDocumentRecord(saveDto.getDocumentCatalogCode(), caseMainInfo, pdfUrl.get("fileUrl"), documentNumber, paramMap, pdfSealUrl, sentDeadLine);
                Map<String, Object> operateMap = operateCaseDocumentRecord(saveDto.getDocumentCatalogCode(), caseSourceRegisterMainInfo, pdfUrl.get("fileUrl"), documentNumber, paramMap, pdfSealUrl, saveDto.getIsMultipleDoc(), saveDto.getBelongDocumentId(), partyId, saveDto.getDocumentTemplateType());
                num = MapUtils.getIntValue(operateMap, "num", 0);
                documentId = MapUtils.getString(operateMap, "documentId", "");
            }
            /*if ("CLOSE-TRIGGER-APPROVAL-PASS".equals(saveDto.getCloseSignal()) && "1".equals(configBusiParamDocumentInfo.getIsApprove())) {
                //审批通过，关联文书签章
                //查询关联文书
                String relationDocumentCatalogCode = configBusiParamDocumentInfo.getRelationDocumentCatalogCode();
                if (StringUtils.isNotBlank(relationDocumentCatalogCode)) {
                    String[] relationDocumentCatalogCodeArr = relationDocumentCatalogCode.split(",");
                    for (String relationDocumentCatalogCodeStr : relationDocumentCatalogCodeArr) {
                        log.info("caseId:{},relationDocumentCatalogCodeStr:{},partyId:{}",caseId,relationDocumentCatalogCodeArr,partyId);
                        CaseDocumentRecord caseDocumentRecord = caseDocumentRecordService.getCaseDocumentRecord(caseId, relationDocumentCatalogCodeStr, partyId);
                        if (caseDocumentRecord != null) {
                            String documentContent = caseDocumentRecord.getDocumentContent();
                            JSONObject jsonObject = JSON.parseObject(documentContent);
                            HashMap<String, Object> jsonMap = new HashMap<>(16);
                            for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                                jsonMap.put(entry.getKey(), entry.getValue());
                            }
                            jsonMap.put("sealDate", DateUtils.formatDate(new Date(), "yyyy年MM月dd日"));
                            //生成文号
                            ConfigBusiParamDocumentInfo relateConfigBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(relationDocumentCatalogCodeStr);
                            String relateDocumentNumber = genDocumentNumber(relationDocumentCatalogCodeStr, saveDto, relateConfigBusiParamDocumentInfo);
                            ConfigBusiParamDocumentInfo configInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(relationDocumentCatalogCodeStr);
                            String relatedDocumentKindCode = configInfo.getDocumentKindCode();

                            //处罚决定书文号更新至案件详情表
                            if (!ObjectUtils.isEmpty(relateDocumentNumber) && (Constant.STRING_KIND_CODE_CFJDS.equals(relatedDocumentKindCode) || Constant.STRING_KIND_CODE_BYCFJDS.equals(relatedDocumentKindCode))) {
                                //判断是否多当事人分别处罚
                                if (caseMainInfoService.checkCaseIsPartiesPartPunish(caseId, null)) {
                                    CaseMainDetailAuxiliaryInfo caseMainDetailAuxiliaryInfo = new CaseMainDetailAuxiliaryInfo();
                                    caseMainDetailAuxiliaryInfo.setCaseId(caseId);
                                    caseMainDetailAuxiliaryInfo.setPartyId(partyId);
                                    caseMainDetailAuxiliaryInfo.setPunishDocumentNumber(relateDocumentNumber);
                                    caseMainDetailAuxiliaryInfoService.updateSpecialParam(caseMainDetailAuxiliaryInfo);
                                } else {
                                    CaseMainDetailInfo caseMainDetailInfo = new CaseMainDetailInfo();
                                    caseMainDetailInfo.setCaseId(caseId);
                                    caseMainDetailInfo.setPunishDocumentNumber(relateDocumentNumber);
                                    caseMainDetailInfoMapper.updateByPrimaryKeySelective(caseMainDetailInfo);
                                }
                            }
                            jsonMap.put("documentNumber", relateDocumentNumber);
                            String relateTemplateCode = getTemplateCodeByDocumentCatalogCode(relationDocumentCatalogCodeStr, caseId, jsonMap);
                            FillAndConvertToPdfRequest relatePdfRequest = new FillAndConvertToPdfRequest();
                            relatePdfRequest.setTemplateCode(relateTemplateCode);
                            relatePdfRequest.setParamMap(jsonMap);
                            Map<String, String> relatePdfUrl = getConvertedPdfUrl(relatePdfRequest);
                            System.out.println("关联文书生成耗时------------------------" + (System.currentTimeMillis() - start));
                            // String fileBase64=;
                            FileSealInfoQueryDto queryDto = new FileSealInfoQueryDto();
                            queryDto.setFileBase64(relatePdfUrl.get("fileBase64"));
                            String relatePdfSealUrl = dealFileSeal(queryDto);
                            System.out.println("关联文书签章耗时------------------------" + (System.currentTimeMillis() - start));
                            //operateCaseDocumentRecord(relationDocumentCatalogCodeStr, caseMainInfo, relatePdfUrl.get("fileUrl"), relateDocumentNumber, paramMap, relatePdfSealUrl, sentDeadLine);
                            operateCaseDocumentRecord(relationDocumentCatalogCodeStr, caseMainInfo, relatePdfUrl.get("fileUrl"), relateDocumentNumber, jsonMap, relatePdfSealUrl, sentDeadLine, saveDto.getIsMultipleDoc(), saveDto.getBelongDocumentId(), partyId, saveDto.getDocumentTemplateType());
                            if (StringUtils.isBlank(pdfSealUrl)) {
                                resultMap.put("success", "false");
                                resultMap.put("msg", "文书签章失败！");
                                return resultMap;
                            }
                        }
                    }
                }
            }*/
        } else {
            //num = operateCaseDocumentRecord(saveDto.getDocumentCatalogCode(), caseMainInfo, pdfUrl.get("fileUrl"), documentNumber, paramMap, pdfSealUrl, sentDeadLine);
            Map<String, Object> operateMap = operateCaseDocumentRecord(saveDto.getDocumentCatalogCode(), caseSourceRegisterMainInfo, pdfUrl.get("fileUrl"), documentNumber, paramMap, pdfSealUrl, saveDto.getIsMultipleDoc(), saveDto.getBelongDocumentId(), partyId, saveDto.getDocumentTemplateType());
            num = MapUtils.getIntValue(operateMap, "num", 0);
            documentId = MapUtils.getString(operateMap, "documentId", "");
        }
        /*if (("CLOSE-TRIGGER-APPROVAL-PASS".equals(saveDto.getCloseSignal()) && "1".equals(configBusiParamDocumentInfo.getIsApprove())) || !"1".equals(configBusiParamDocumentInfo.getIsApprove())) {
            //处罚决定撤销时相关流程更新
            CasePunishDecisionRevokeRecordVo vo = casePunishDecisionRevokeRecordService.getCasePunishDecisionRevokeRecordBasicInfo(caseId);
            if(!ObjectUtils.isEmpty(vo)){
                String revokeReasonCode = vo.getRevokeReasonCode();
                if(PunishDecisionRevokeReasonEnum.FYSSHCX.getCode().equals(revokeReasonCode)){
                    //没有行政处罚撤销决定书
                    if(Constant.STRING_KIND_CODE_XZCFCXSPB.equals(documentKindCode)){
                        casePunishDecisionRevokeRecordService.dealAfterPunishRevoke(caseId,vo.getDealAfterRevokeTypeCode());
                    }
                }
            }
        }*/
        //操作文书记录表 判断文书记录是否存在，存在则添加历史表，然后更新数据
        if (num < 1) {
            resultMap.put("success", "false");
            resultMap.put("msg", "保存失败！");
            return resultMap;
        }
        //送达回证特殊处理
        /*String receiptDocUrl = pdfSealUrl;
        if (YesOrNoEnum.YES.getCode().equals(isGetBlankDoc)) {
            //空白送达回证无需签章
            receiptDocUrl = noSealPdfUrl;
        } else {
            receiptDocUrl = pdfSealUrl;
        }*/
        //updateDocumentRecordInfoAfterSentReceiptPrint(documentCatalogCode, pdfUrl, receiptDocUrl, caseId, isGetBlankDoc, partyId);
        System.out.println("送达回证特殊处理耗时------------------------" + (System.currentTimeMillis() - start));
        //非诉执行立案申请
        //nonLitigationExecute(saveDto);
        //案件状态变更操作
       // updateCaseStatusChange(saveDto, documentId, configBusiParamDocumentInfo);
        //若需要更新则根据配置更新相关数据
        /*if (!YesOrNoEnum.NO.getCode().equals(saveDto.getIsUpdateRelationTable())) {
            operateBusiTableByDocumentCatalogCode(saveDto);
        }*/
       /* String closeSignal = saveDto.getCloseSignal();
        if (StringUtils.isBlank(closeSignal)) {
            closeSignal = "CLOSE-TRIGGER-DOCCREATE";
        }
        resultMap.put("closeSignal", closeSignal);
        //简易程序案件流程无需滚动,不设置workId
        //非简易程序时设置workId
        if (!CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseMainInfo.getCaseType())) {
            resultMap.put("workId", caseId);
        }*/
        resultMap.put("documentId", documentId);
        resultMap.put("documentCatalogCode", documentCatalogCode);
        // 证据库案件信息同步对接
        try {
            String la = "LASPB";
            if (saveDto.getDocumentCatalogCode().contains(la) && StringUtils.isNotBlank(documentNumber)) {
                // 换为证据库新API
                evidenceInventoryService.saveEvent(saveDto.getCaseSourceId(), documentNumber);
            }
        } catch (Exception e) {
            log.info("证据库立案对接失败:{}", e.getMessage());
        }
        return resultMap;
    }

    /**
     * 根据条件生成文号
     *
     * @param saveDto
     * @param configBusiParamDocumentInfo
     * @return {@link String}
     * @author liyafeng
     * @date 2022/3/12
     */
    private String genDocumentNumber(String documentCatalogCode, CSourceDocCommonOperateSaveDto saveDto, ConfigBusiParamDocumentInfo configBusiParamDocumentInfo) {
        String documentNumber = "";
        //判断文号是否已生成
        CaseSourceDocumentRecord caseSourceDocumentRecord = null;
        if (StringUtils.isBlank(saveDto.getIsMultipleDoc()) || Constant.STRING_0.equals(saveDto.getIsMultipleDoc())) {
            caseSourceDocumentRecord = caseSourceDocumentRecordService.getCaseDocumentRecord(saveDto.getCaseSourceId(), documentCatalogCode, saveDto.getPartyId());
        }
        if (StringUtils.isNotBlank(saveDto.getIsMultipleDoc()) && Constant.STRING_1.equals(saveDto.getIsMultipleDoc()) && StringUtils.isNotBlank(saveDto.getBelongDocumentId())) {
            caseSourceDocumentRecord = caseSourceDocumentRecordMapper.selectByPrimaryKey(saveDto.getBelongDocumentId());
        }
        if (null != caseSourceDocumentRecord && StringUtils.isNotBlank(caseSourceDocumentRecord.getDocumentNumber())) {
            documentNumber = caseSourceDocumentRecord.getDocumentNumber();
            return documentNumber;
        }
        String docNoGene = configBusiParamDocumentInfo.getDocNoGene();
        if ("1".equals(docNoGene)) {
            //审批前
            documentNumber = getDocumentNumber(saveDto.getCaseSourceId(), documentCatalogCode);
        } else if ("CLOSE-TRIGGER-APPROVAL-PASS".equals(saveDto.getCloseSignal()) && "1".equals(configBusiParamDocumentInfo.getIsApprove())) {
            //审批完成后
            documentNumber = getDocumentNumber(saveDto.getCaseSourceId(), documentCatalogCode);
        } else if (Constant.STRING_1.equals(configBusiParamDocumentInfo.getIsGenDocnum())) {
            documentNumber = getDocumentNumber(saveDto.getCaseSourceId(), documentCatalogCode);
        }
        return documentNumber;
    }

    /**
     * 描述：送达回证打印后更新文书记录信息
     *
     * @param documentCatalogCode 文书目录编码
     * @param pdfUrl              送达回证文书pdf信息
     * @param pdfSealUrl          签章后送达回证文书pdf信息
     * @param caseId              案件id
     * @param isGetBlankDoc       是否获取空白文书
     * @param partyId             当事人id
     * @author xiangyuyu
     * @date 2022-03-12 16:00
     */
    private void updateDocumentRecordInfoAfterSentReceiptPrint(String documentCatalogCode, Map<String, String> pdfUrl, String pdfSealUrl, String caseId, String isGetBlankDoc, String partyId) {
        //先校验文书是否为送达回证
       /* ConfigBusiParamDocumentInfo configBusiParamDocumentInfo
                = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
        if (ObjectUtils.isEmpty(configBusiParamDocumentInfo)) {
            throw new BusinessException("非法的文书目录编码：" + documentCatalogCode);
        }
        String documentKindCode = configBusiParamDocumentInfo.getDocumentKindCode();
        if (Constant.STRING_KIND_CODE_SDHZ.equals(documentKindCode)) {
            String sentReceiptPdfUrl = "";
            if (!ObjectUtils.isEmpty(pdfSealUrl)) {
                sentReceiptPdfUrl = pdfSealUrl;
            } else {
                if (ObjectUtils.isEmpty(pdfUrl) || pdfUrl.size() == 0) {
                } else {
                    sentReceiptPdfUrl = pdfUrl.get("fileUrl");
                    if (ObjectUtils.isEmpty(sentReceiptPdfUrl)) {
                        log.error("未找到送达回证文书pdf地址为空");
                    }
                }
            }
            //获取xx送达回证的文书记录
            CaseDocumentRecord caseDocumentRecord = caseDocumentRecordService.getCaseDocumentRecord(caseId, documentCatalogCode, partyId);
            if (!ObjectUtils.isEmpty(caseDocumentRecord)) {
                CaseDocumentRecord newRecord = new CaseDocumentRecord();
                newRecord.setId(caseDocumentRecord.getId());
                if (YesOrNoEnum.YES.getCode().equals(isGetBlankDoc)) {
                    newRecord.setDocumentUrlBlank(sentReceiptPdfUrl);
                } else {
                    newRecord.setDocumentUrl(sentReceiptPdfUrl);
                }
                caseDocumentRecordMapper.updateByPrimaryKeySelective(newRecord);
            }
        }*/
    }

    /**
     * 描述：强制执行申请书生成后发送至法院非诉执行立案申请
     *
     * @param saveDto 保存dto
     * @author shishengyao
     * @date 2022/04/10
     */
    private void nonLitigationExecute(StageDocCommonOperateSaveDto saveDto) {
        if ("QZZXSQS".equals(saveDto.getDocumentKindCode())) {
            CaseNonLitigationExecuteRequestDto requestDto = new CaseNonLitigationExecuteRequestDto();
            requestDto.setCaseId(saveDto.getCaseId());
            Map<String, Object> result = caseNonLitigationExecuteRecordService.nonLitigationExecuteRegister(requestDto);
            if (Constant.STRING_FAIL_EN.equals(result.get("code"))) {
                throw new BusinessException(result.get("errorMsg").toString());
            }
        }
    }

    /**
     * 根据配置更新相关数据
     *
     * @param saveDto
     * @return
     * @author liyafeng
     * @date 2022/3/1
     */
    private void operateBusiTableByDocumentCatalogCode(StageDocCommonOperateSaveDto saveDto) {
        List<BusiTableOperateVo> busiTableOperateVoList = configBusiParamDocumentColumnMapper.selectTableNameListByDocumentCatalogCode(saveDto.getDocumentCatalogCode());
        if (null != busiTableOperateVoList && busiTableOperateVoList.size() > 0) {
            for (BusiTableOperateVo busiTableOperateVo : busiTableOperateVoList) {
                Example example = new Example(ConfigBusiParamDocumentColumn.class);
                example.createCriteria().andEqualTo("documentCatalogCode", saveDto.getDocumentCatalogCode()).andEqualTo("busiTableNameEn", busiTableOperateVo.getBusiTableNameEn()).andEqualTo("busiOperateType", busiTableOperateVo.getBusiOperateType());
                List<ConfigBusiParamDocumentColumn> configBusiParamDocumentColumnList = configBusiParamDocumentColumnMapper.selectByExample(example);
                if ("U".equals(busiTableOperateVo.getBusiOperateType())) {
                    updateBusiTable(busiTableOperateVo, busiTableOperateVoList, saveDto, configBusiParamDocumentColumnList);
                }
                if ("I,U".equals(busiTableOperateVo.getBusiOperateType())) {
                    //先判断是否存在
                    String selectSql = "select count(1) from upcase." + busiTableOperateVo.getBusiTableNameEn() + " where case_id='" + saveDto.getCaseId() + "'";
                    ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(saveDto.getDocumentCatalogCode());
                    String documentKindCode = configBusiParamDocumentInfo.getDocumentKindCode();
                    if (Constant.STRING_KIND_CODE_SDDZQRS.equals(documentKindCode)) {
                        selectSql = selectSql.concat(" and party_id = '" + saveDto.getPartyId() + "'");
                    }
                    if (CaseStatusChangeTypeEnum.isCaseChangeDocEnum(documentKindCode)) {
                        selectSql = selectSql.concat(" and case_change_type = '" + CaseStatusChangeTypeEnum.getEnumByDocumentKindCode(documentKindCode).getCode() + "'");
                    }
                    int num = configBusiParamDocumentColumnMapper.executeSelectNumSql(selectSql);
                    if (num > 0) {
                        //存在则更新
                        updateBusiTable(busiTableOperateVo, busiTableOperateVoList, saveDto, configBusiParamDocumentColumnList);

                    } else {
                        //不存在则插入
                        Map<String, String> insertMap = new HashMap<>();
                        //组装map
                        for (ConfigBusiParamDocumentColumn configBusiParamDocumentColumn : configBusiParamDocumentColumnList) {
                            if ("id".equals(configBusiParamDocumentColumn.getBusiOperateCondition())) {
                                insertMap.put(configBusiParamDocumentColumn.getBusiColumnEn(), StringUtils.uuid());
                                continue;
                            }
                            if ("case_id".equals(configBusiParamDocumentColumn.getBusiOperateCondition())) {
                                insertMap.put(configBusiParamDocumentColumn.getBusiColumnEn(), saveDto.getCaseId());
                                continue;
                            }
                            if ("document_catalog_code".equals(configBusiParamDocumentColumn.getBusiOperateCondition())) {
                                insertMap.put(configBusiParamDocumentColumn.getBusiColumnEn(), saveDto.getDocumentCatalogCode());
                                continue;
                            }
                            if ("create_time".equals(configBusiParamDocumentColumn.getBusiOperateCondition())) {
                                insertMap.put(configBusiParamDocumentColumn.getBusiColumnEn(), DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
                                continue;
                            }
                            //---送达方式及地址确认书使用start---
                            if ("party_id".equals(configBusiParamDocumentColumn.getBusiOperateCondition())) {
                                insertMap.put(configBusiParamDocumentColumn.getBusiColumnEn(), saveDto.getPartyId());
                                continue;
                            }
                            /*if ("status".equals(configBusiParamDocumentColumn.getBusiOperateCondition())) {
                                insertMap.put(configBusiParamDocumentColumn.getBusiColumnEn(), null);//默认设置为空，签字确认后修改为1
                                continue;
                            }*/
                            //---送达方式及地址确认书使用end---

                            String columnValue = "";
                            try {
                                //columnValue = saveDto.getDataMap().get(configBusiParamDocumentColumn.getDocumentTemplateFieldEn()).toString();
                                columnValue = MapUtils.getString(saveDto.getDataMap(), configBusiParamDocumentColumn.getDocumentTemplateFieldEn(), "");
                            } catch (Exception e) {
                                throw new BusinessException(configBusiParamDocumentColumn.getDocumentTemplateFieldCn() + "为空");
                            }
                            insertMap.put(configBusiParamDocumentColumn.getBusiColumnEn(), columnValue);
                        }
                        //生成INSERT INTO table(field1,field2) 部分
                        StringBuffer sbField = new StringBuffer();
                        //生成VALUES('value1','value2') 部分
                        StringBuffer sbValue = new StringBuffer();
                        sbField.append("INSERT INTO  upcase." + busiTableOperateVo.getBusiTableNameEn() + "(");
                        for (Map.Entry<String, String> entry : insertMap.entrySet()) {
                            String mapKey = entry.getKey();
                            String mapValue = entry.getValue();
                            mapValue=mapValue.replace("'","''");
                            sbField.append(mapKey + ",");
                            sbValue.append("'" + mapValue + "',");
                        }
                        sbField = sbField.deleteCharAt(sbField.length() - 1);
                        sbValue = sbValue.deleteCharAt(sbValue.length() - 1);
                        String insertSql = sbField.toString() + ") VALUES(" + sbValue.toString() + ")";
                        configBusiParamDocumentColumnMapper.executeInsertSql(insertSql);
                    }


                }
            }
        }
    }

    /**
     * 更新操作
     *
     * @param busiTableOperateVo
     * @param busiTableOperateVoList
     * @param saveDto
     * @param configBusiParamDocumentColumnList
     * @return
     * @author liyafeng
     * @date 2022/3/11
     */
    private void updateBusiTable(BusiTableOperateVo busiTableOperateVo, List<BusiTableOperateVo> busiTableOperateVoList, StageDocCommonOperateSaveDto saveDto, List<ConfigBusiParamDocumentColumn> configBusiParamDocumentColumnList) {
        String tableName = busiTableOperateVo.getBusiTableNameEn();
        String caseId = saveDto.getCaseId();
        String setSql = "";
        for (ConfigBusiParamDocumentColumn configBusiParamDocumentColumn : configBusiParamDocumentColumnList) {
            //BusiOperateCondition 不为空 此字段不更新
            if (StringUtils.isNotBlank(configBusiParamDocumentColumn.getBusiOperateCondition())) {
                continue;
            }
            String columnValue = "";
            try {
                columnValue = saveDto.getDataMap().get(configBusiParamDocumentColumn.getDocumentTemplateFieldEn()).toString();
                columnValue= columnValue.replace("'","''");
            } catch (Exception e) {
                //前端没有传key值，此字段不更新
                if (saveDto.getDataMap().get(configBusiParamDocumentColumn.getDocumentTemplateFieldEn()) == null)
                    continue;

                throw new BusinessException(configBusiParamDocumentColumn.getDocumentTemplateFieldCn() + "为空");
            }
            if (StringUtils.isBlank(setSql)) {
                setSql = configBusiParamDocumentColumn.getBusiColumnEn() + "='" + columnValue + "'";
            } else {
                setSql = setSql + "," + configBusiParamDocumentColumn.getBusiColumnEn() + "='" + columnValue + "'";
            }
        }
        String updateSql = "update upcase." + tableName + " set " + setSql + " where " + " case_id='" + caseId + "'";

        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(saveDto.getDocumentCatalogCode());
        if (Constant.STRING_KIND_CODE_SDDZQRS.equals(configBusiParamDocumentInfo.getDocumentKindCode())) {
            updateSql = updateSql.concat(" and party_id = '" + saveDto.getPartyId() + "'");
        }
        //案件操作文书
        if (CaseStatusChangeTypeEnum.isCaseChangeDocEnum(configBusiParamDocumentInfo.getDocumentKindCode())) {
            updateSql = updateSql.concat(" and case_change_type = '" + CaseStatusChangeTypeEnum.getEnumByDocumentKindCode(configBusiParamDocumentInfo.getDocumentKindCode()).getCode() + "'");
        }
        configBusiParamDocumentColumnMapper.executeUpdateSql(updateSql);
    }


    /**
     * 根据文书目录编码获取法人或个人文件模板code
     *
     * @param documentCatalogCode
     * @return {@link String}
     * @author liyafeng
     * @date 2022/3/1
     */
    @Override
    public String getTemplateCodeByDocumentCatalogCode(String documentCatalogCode, String caseSourceId, Map<String, Object> paramMap) {
        String templateCode="";
        ConfigBusiParamDocumentInfo detailResult = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
        if (ObjectUtil.isNotEmpty(detailResult)) {
            //根据当事人类型获取对应的模板
            List<CaseSourcePartyInfoVo> caseSourcePartyInfos = caseSourcePartyInfoService.getCaseSourcePartyInfo(caseSourceId);
            if (null != caseSourcePartyInfos && caseSourcePartyInfos.size() > 0) {
                CaseSourcePartyInfoVo caseSourcePartyInfoVo = caseSourcePartyInfos.get(0);
                if ("1".equals(caseSourcePartyInfoVo.getPartyType())) {
                    //个人
                    templateCode = detailResult.getTemplatePersonCode();
                } else {
                    //法人
                    templateCode = detailResult.getTemplateLegalCode();
                }
            }else {
                //个人
                templateCode = detailResult.getTemplatePersonCode();
            }
        }
        return templateCode;
    }

    /**
     * 操作文书记录表
     *
     * @param documentCatalogCode        文件目录的代码
     * @param caseSourceRegisterMainInfo
     * @param convertedPdfUrl
     * @param documentNumber
     * @param paramMap
     * @param pdfSealUrl                 pdf印网址
     * @param isMultipleDoc              是多个文档
     * @param belongDocumentId           属于文档id
     * @param partyId                    当事人id
     * @param documentTemplateType       文书模板类型
     * @return {@link Map<String, Object> }
     * @author shishengyao
     * @date 2022/08/24
     */
    private Map<String, Object> operateCaseDocumentRecord(String documentCatalogCode, CaseSourceRegisterMainInfo caseSourceRegisterMainInfo, String convertedPdfUrl, String documentNumber, Map<String, Object> paramMap, String pdfSealUrl, String isMultipleDoc, String belongDocumentId, String partyId, String documentTemplateType) {

        //String handleType = caseMainInfo.getHandleType();
        Map<String, Object> operateMap = new HashMap<>();
        //根据目录编码查询
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
        String documentKindCode = configBusiParamDocumentInfo.getDocumentKindCode();
        int num = 0;
        UserDTO userDTO = null;
        try {
            userDTO = UserUtil.getUserInfo();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (ObjectUtils.isEmpty(userDTO)) {
            userDTO = new UserDTO();
            userDTO.setUserId(0L);
            userDTO.setRealName("系统");
        }
        //判断文书记录是否存在
        Example example = new Example(CaseSourceDocumentRecord.class);
        Example.Criteria c = example.createCriteria();
        boolean isNeedPartyIdInfo = false;
        if (sentRelatedNeedPartyIdDocumentKindCodeList.contains(documentKindCode)) {
            isNeedPartyIdInfo = true;
        }
        if (StringUtils.isBlank(isMultipleDoc) || Constant.STRING_0.equals(isMultipleDoc) || StringUtils.isBlank(belongDocumentId)) {
            if (DocumentKindEnum.DOC_KIND_LASPB.getCode().equals(configBusiParamDocumentInfo.getDocumentKindCode())) {
                c.andEqualTo("caseSourceId", caseSourceRegisterMainInfo.getId()).andEqualTo("documentCatalogCode", documentCatalogCode);
            } else {
                //非多条文书记录
                c.andEqualTo("caseSourceId", caseSourceRegisterMainInfo.getId()).andEqualTo("documentCatalogCode", documentCatalogCode);
                if (!ObjectUtils.isEmpty(partyId)) {
                    if (isNeedPartyIdInfo) {
                        c.andEqualTo("partyId", partyId);
                    }
                }
            }
        } else if (StringUtils.isNotBlank(belongDocumentId)) {
            c.andEqualTo("caseSourceId", caseSourceRegisterMainInfo.getId()).andEqualTo("documentCatalogCode", documentCatalogCode).andEqualTo("id", belongDocumentId);
        }
        //c.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
        c.andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
        List<CaseSourceDocumentRecord> caseSourceDocumentRecords = caseSourceDocumentRecordMapper.selectByExample(example);
        if ((StringUtils.isBlank(isMultipleDoc) || Constant.STRING_0.equals(isMultipleDoc)) || (StringUtils.isNotBlank(belongDocumentId) && Constant.STRING_1.equals(isMultipleDoc))) {
            // 特殊处理中止审批表
            boolean suspendUpdateFlag = true;
            if (null != caseSourceDocumentRecords && caseSourceDocumentRecords.size() > 0 && suspendUpdateFlag) {
                //不为空，则添加历史，更新记录
                for (CaseSourceDocumentRecord caseSourceDocumentRecord : caseSourceDocumentRecords) {
                    //添加历史
                    //todo
                    CaseSourceDocumentRecordHis caseSourceDocumentRecordHis = new CaseSourceDocumentRecordHis();
                    BeanUtils.copyProperties(caseSourceDocumentRecord, caseSourceDocumentRecordHis);
                    caseSourceDocumentRecordHis.setId(StringUtils.uuid());
                    caseSourceDocumentRecordHis.setRecordId(caseSourceDocumentRecord.getId());
                    caseSourceDocumentRecordHis.setOp("update");
                    caseSourceDocumentRecordHis.setHisCreateTime(new Date());
                    caseSourceDocumentRecordHisMapper.insert(caseSourceDocumentRecordHis);
                    //更新文书记录表
                    CaseSourceDocumentRecord updateCaseSourceDocumentRecord = new CaseSourceDocumentRecord();
                    updateCaseSourceDocumentRecord.setId(caseSourceDocumentRecord.getId());
                    updateCaseSourceDocumentRecord.setDocumentUrl(convertedPdfUrl);
                    //updateCaseDocumentRecord.setDocumentCreateTime(LocalDateTime.now());
                    //updateCaseDocumentRecord.setDocumentApprovalStatus(saveDto.getDocumentApprovalStatus());
                    updateCaseSourceDocumentRecord.setDocumentUrlAfterSeal(pdfSealUrl);
                    updateCaseSourceDocumentRecord.setSentDeadline(null);
                    updateCaseSourceDocumentRecord.setDocumentNumber(documentNumber);
                    updateCaseSourceDocumentRecord.setDocumentContent(JSONObject.toJSON(paramMap).toString());

                    updateCaseSourceDocumentRecord.setPartyId(partyId);//设置当事人id
                    updateCaseSourceDocumentRecord.setDocumentRecordStatus(DocumentRecordStatusEnum.NORMAL.getCode());//设置文书为正常状态
                    if (!ObjectUtils.isEmpty(documentTemplateType)) { //设置模板类型
                        updateCaseSourceDocumentRecord.setDocumentTemplateType(documentTemplateType);
                    }
                    updateCaseSourceDocumentRecord.setCreateUserName(userDTO.getRealName());
                    updateCaseSourceDocumentRecord.setCreateUserId(userDTO.getUserId().toString());
                    num = caseSourceDocumentRecordMapper.updateByPrimaryKeySelective(updateCaseSourceDocumentRecord);
                    operateMap.put("num", num);
                    operateMap.put("documentId", caseSourceDocumentRecord.getId());
                }
                return operateMap;
            } else {
                CaseSourceDocumentRecord caseSourceDocumentRecord = new CaseSourceDocumentRecord();
                caseSourceDocumentRecord.setCaseSourceId(caseSourceRegisterMainInfo.getId());
                caseSourceDocumentRecord.setId(StringUtils.uuid());
                caseSourceDocumentRecord.setDocumentCatalogCode(documentCatalogCode);
                caseSourceDocumentRecord.setDocumentUrl(convertedPdfUrl);
                caseSourceDocumentRecord.setSentDeadline(null);
                caseSourceDocumentRecord.setDocumentCreateTime(LocalDateTime.now());
                caseSourceDocumentRecord.setDocumentContent(JSONObject.toJSON(paramMap).toString());
                //生成默认待提交状态
                if ("1".equals(configBusiParamDocumentInfo.getIsApprove())) {
                    caseSourceDocumentRecord.setDocumentApprovalStatus(DocumentStatusEnum.WAIT_TO_SUBMIT.getCode());
                    caseSourceDocumentRecord.setDocumentAuditStatus("notSubmit");
                }
                if ("1".equals(configBusiParamDocumentInfo.getIsSend())) {
                    caseSourceDocumentRecord.setDocumentSentStatus(DocumentStatusEnum.WAIT_TO_SEND.getCode());
                }
                if (BusinessContextUtil.documentNeedConfirm(configBusiParamDocumentInfo)) {
                    caseSourceDocumentRecord.setDocumentSignstampedStatus(DocumentStatusEnum.WAIT_TO_CONFIRM.getCode());
                }
                caseSourceDocumentRecord.setDocumentNumber(documentNumber);
                caseSourceDocumentRecord.setCreateUserName(userDTO.getRealName());
                caseSourceDocumentRecord.setCreateUserId(userDTO.getUserId().toString());
                caseSourceDocumentRecord.setDocumentUrlAfterSeal(pdfSealUrl);
                caseSourceDocumentRecord.setDocumentRecordStatus(DocumentRecordStatusEnum.NORMAL.getCode());//设置文书为正常状态
                if (!ObjectUtils.isEmpty(documentTemplateType)) { //设置模板类型
                    caseSourceDocumentRecord.setDocumentTemplateType(documentTemplateType);
                }
                if (!ObjectUtils.isEmpty(partyId)) {
                    //设置当事人id
                    caseSourceDocumentRecord.setPartyId(partyId);
                }
                num = caseSourceDocumentRecordMapper.insert(caseSourceDocumentRecord);
                operateMap.put("num", num);
                operateMap.put("documentId", caseSourceDocumentRecord.getId());
                return operateMap;
            }
        }
        CaseSourceDocumentRecord caseSourceDocumentRecord = new CaseSourceDocumentRecord();
        caseSourceDocumentRecord.setCaseSourceId(caseSourceRegisterMainInfo.getId());
        caseSourceDocumentRecord.setId(StringUtils.uuid());
        caseSourceDocumentRecord.setDocumentCatalogCode(documentCatalogCode);
        caseSourceDocumentRecord.setDocumentUrl(convertedPdfUrl);
        caseSourceDocumentRecord.setSentDeadline(null);
        caseSourceDocumentRecord.setDocumentCreateTime(LocalDateTime.now());
        caseSourceDocumentRecord.setDocumentContent(JSONObject.toJSON(paramMap).toString());
        //生成默认待提交状态
        if ("1".equals(configBusiParamDocumentInfo.getIsApprove())) {
            caseSourceDocumentRecord.setDocumentApprovalStatus(DocumentStatusEnum.WAIT_TO_SUBMIT.getCode());
            caseSourceDocumentRecord.setDocumentAuditStatus("notSubmit");
        }
        if ("1".equals(configBusiParamDocumentInfo.getIsSend())) {
            caseSourceDocumentRecord.setDocumentSentStatus(DocumentStatusEnum.WAIT_TO_SEND.getCode());
        }
        if (BusinessContextUtil.documentNeedConfirm(configBusiParamDocumentInfo)) {
            caseSourceDocumentRecord.setDocumentSignstampedStatus(DocumentStatusEnum.WAIT_TO_CONFIRM.getCode());
        }
        caseSourceDocumentRecord.setDocumentNumber(documentNumber);
        caseSourceDocumentRecord.setCreateUserName(userDTO.getRealName());
        caseSourceDocumentRecord.setCreateUserId(userDTO.getUserId().toString());
        caseSourceDocumentRecord.setDocumentUrlAfterSeal(pdfSealUrl);
        caseSourceDocumentRecord.setDocumentRecordStatus(DocumentRecordStatusEnum.NORMAL.getCode());//设置文书为正常状态
        if (!ObjectUtils.isEmpty(partyId)) {
            //设置当事人id
            caseSourceDocumentRecord.setPartyId(partyId);
        }
        if (!ObjectUtils.isEmpty(documentTemplateType)) { //设置模板类型
            caseSourceDocumentRecord.setDocumentTemplateType(documentTemplateType);
        }
        num = caseSourceDocumentRecordMapper.insert(caseSourceDocumentRecord);

        operateMap.put("num", num);
        operateMap.put("documentId", caseSourceDocumentRecord.getId());
        return operateMap;
    }

    /**
     * 获取文书html和配置字段公共方法
     *
     * @param request
     * @return {@link Result< String>}
     * @author liyafeng
     * @date 2022/2/18
     */
    @Override
    public DocumentCommonFormHtmlVo getDocumentFormHtml(CSourceDocCommonHtmlRequest request) {
        DocumentCommonFormHtmlVo vo = new DocumentCommonFormHtmlVo();
        Map<String, Object> templateDetail = getTemplateDetail(request.getDocumentCatalogCode(), request.getCaseSourceId(),null);
        Map<String, Object> objectMap = JSON.parseObject(templateDetail.get("templateFieldConfigs").toString());
        vo.setHtmlContent(templateDetail.get("htmlContent") == null ? "" : templateDetail.get("htmlContent").toString());
        vo.setTemplateConfigMap(objectMap);
        return vo;
    }

    @Override
    public DocumentCommonFormDataVo getCommonDocumentFormData(CSourceDocCommonHtmlRequest request) {
        DocumentCommonFormDataVo vo = new DocumentCommonFormDataVo();
        Map<String, Object> resultData = new HashMap<>();
        //查询历史记录
        CaseSourceDocumentRecord recordInfo = caseSourceDocumentRecordService.getCaseDocumentRecord(request.getCaseSourceId(), request.getDocumentCatalogCode(), request.getPartyId());
        if (ObjectUtil.isNotEmpty(recordInfo) && ObjectUtil.isNotEmpty(recordInfo.getDocumentContent())) {
            String documentContent = "";
            ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(request.getDocumentCatalogCode());
            String documentKindCode = configBusiParamDocumentInfo.getDocumentKindCode();
            documentContent = recordInfo.getDocumentContent();
            resultData = JSON.parseObject(documentContent);
            vo.setOperateType(RecordSaveTypeEnum.MOD.getCode());
        } else {
            //查询是否 有暂存
            CaseTemporaryRecord record = caseTemporaryRecordService.getRecord(request.getCaseSourceId(), request.getDocumentCatalogCode(), request.getPartyId());
            if (record != null) {
                JSONObject json = JSONObject.parseObject(record.getContent());
                vo.setDataMap(json.getJSONObject("dataMap"));
                vo.setOperateType(RecordSaveTypeEnum.TEMP.getCode());
                return vo;
            }

            //初次获取数据
            dealCommonDocumentFormData(request, resultData);
            //暂存end
            vo.setOperateType(RecordSaveTypeEnum.ADD.getCode());

        }
        vo.setDataMap(resultData);
        return vo;
    }


    private void dealCommonDocumentFormData(CSourceDocCommonHtmlRequest request, Map<String, Object> resultData) {
        Map<String, Object> templateDetail = getTemplateDetail(request.getDocumentCatalogCode(), request.getCaseSourceId(),null);
        //根据表名，分组查询所需字段数据，放入一个map中
        Map<String, String> sourceDataMap =new HashMap<>();
        if (ObjectUtil.isNotEmpty(templateDetail.get("sourceFieldInfos"))){
            Map<String, Object> sourceFieldInfos = JSON.parseObject(templateDetail.get("sourceFieldInfos").toString());
            // 从表中获取数据
           sourceDataMap = getSourceDataMap(sourceFieldInfos, request);
        }
        if (ObjectUtil.isNotEmpty(templateDetail.get("templateFieldConfigs"))){
            Map templateFieldConfigs = JSON.parseObject(templateDetail.get("templateFieldConfigs").toString());
            Set<String> templateConfigSet = templateFieldConfigs.keySet();
            //循环给自动填充的字段赋值
            for (String configKey : templateConfigSet) {
                String value = "";
                JSONObject paramMap = JSON.parseObject(templateFieldConfigs.get(configKey).toString());
                if (ObjectUtil.isNotEmpty(paramMap.get("isAutoData")) && Constant.WHETHER_STRING_YES.equals(paramMap.get("isAutoData"))) {
                    String dataGenerateRule = paramMap.getString("dataGenerateRule");
                    //自动数据来源，SOURCE_ARTIFICIAL页面填充，SOURCE_SYSTEM系统字段
                    if ("SOURCE_ARTIFICIAL".equals(paramMap.getString("autoDataSource"))) {
                        value = dataGenerateRule;
                    } else if ("SOURCE_SYSTEM".equals(paramMap.getString("autoDataSource"))) {
                        //组装参数结果
                        value = ParseTextUtil.parseText(dataGenerateRule, sourceDataMap);
                        //格式化日期控件
                        if ("3".equals(paramMap.get("controlType"))) {
//                            //日期格式 date ，时间time，日期时间datetime  "timeShow":"yyyy年MM月dd日 hh时mm分ss秒"
                            JSONObject dateConfig = paramMap.getJSONObject("controlConfigContent");
                            String pickerType = dateConfig.getString("pickerType");
                            String timeShow = dateConfig.getString("timeShow");
                            value= DateUtil.formatDate(value,timeShow,pickerType);
                        } else if ("SOURCE_SYSTEM_List".equals(paramMap.getString("autoDataSource"))) {

                        }
                    }
                    resultData.put(paramMap.getString("templateFieldEn"), value);
                }
                // 控件类型是签名 获取执法人员签名
                if (ObjectUtil.isNotEmpty(paramMap.getString("controlType"))) {

                }
            }
        }

    }

    /**
     * 根据模板字段配置信息，组装查询所需要的字段，并组装成map格式
     *
     * @param sourceFieldInfos 源字段信息
     * @param request          请求
     * @return {@link Map<String, String> }
     * @author shishengyao
     * @date 2022/02/28
     */
    private Map<String, String> getSourceDataMap(Map<String, Object> sourceFieldInfos, CSourceDocCommonHtmlRequest request) {
        Map<String, String> sourceDataMap = new HashMap<>();
        Set<String> keySet = sourceFieldInfos.keySet();

        CaseSourceRegisterMainInfo caseSourceRegisterMainInfo = caseSourceRegisterMainInfoMapper.selectByPrimaryKey(request.getCaseSourceId());
        String orgCode=caseSourceRegisterMainInfo.getHandleOrgCode();
        String deptCode=caseSourceRegisterMainInfo.getHandleDeptCode();
        if (ObjectUtil.isEmpty(orgCode)){
            orgCode=caseSourceRegisterMainInfo.getCreateUserOrgCode();
            deptCode=caseSourceRegisterMainInfo.getCreateUserDeptCode();
        }
        for (String tableName : keySet) {
            List<String> fieldList = JSONObject.parseArray(sourceFieldInfos.get(tableName).toString(), String.class);
            String fieldSql = StringUtils.join(fieldList, ",");
            String conditionSql = "";
            String whereSql = "case_source_id=" + "'" + request.getCaseSourceId() + "'";
            if ("case_main_info".equals(tableName)) {
                conditionSql = " from upcase." + tableName;
                whereSql = "id=" + "'" + request.getCaseSourceId() + "'";
            } else if ("case_parties_person_info".equals(tableName)
                    || "case_parties_legal_info".equals(tableName)
                    || "case_parties_record".equals(tableName)) {
                List<String> packFieldList = new ArrayList<>();
                for (String field : fieldList) {
                    String packField = " string_agg ( " + field + ", '、' order by party_type,create_time  desc ) as " + field;
                    packFieldList.add(packField);
                }
                fieldSql = StringUtils.join(packFieldList, ",");
                if ("case_parties_record".equals(tableName)) {
                    conditionSql = " from upcase." + tableName + " cpr ";
                } else {
                    conditionSql = " from upcase." + tableName + " left join upcase.case_parties_record cpr on cpr.party_id=" + tableName + ".id";
                }
                whereSql = "case_id=" + "'" + request.getCaseSourceId() + "'" + " and cpr.status='1' ";
                if (!ObjectUtils.isEmpty(request.getPartyId())) {
                    whereSql = whereSql.concat(" and cpr.party_id = '" + request.getPartyId() + "'");
                }
            } else if ("case_reason_main_record".equals(tableName)) {
                List<String> packFieldList = new ArrayList<>();
                for (String field : fieldList) {
                    String packField = " string_agg ( " + field + ", ',' order by " + field + " ASC) as " + field;
                    packFieldList.add(packField);
                }
                fieldSql = StringUtils.join(packFieldList, ",");
                conditionSql = " from upcase." + tableName;
                whereSql = "case_id=" + "'" + request.getCaseSourceId() + "'" + "and status='1'";
            } else if ("sys_depart_param".equals(tableName)) {
                conditionSql = " from upcase." + tableName;
                whereSql = "org_code=" + "'" + orgCode + "' and dept_code="+ "'" + deptCode + "' and is_deleted='0'";

            } else {
                if (tableName.contains("csource.")){
                    conditionSql = " from " + tableName;
                    if ("csource.case_source_register_main_info".equals(tableName)){
                        whereSql = "id=" + "'" + request.getCaseSourceId() + "'";
                    }
                    if ("csource.case_source_party_info".equals(tableName)){
                        whereSql = "id=" + "'" + request.getPartyId() + "'";
                    }


                }else {
                    conditionSql = " from upcase." + tableName;
                }


            }
            Map<String, Object> dataMap = new HashMap<>();
            String sqlStr = "select " + fieldSql + conditionSql + " where " + whereSql + " limit 1";
            if (StringUtils.isNotEmpty(conditionSql)) {
                dataMap = cSourceDocCommonOperateMapper.getDataMap(sqlStr);
            }
            if("sys_depart_param".equals(tableName)&&ObjectUtils.isEmpty(dataMap)){
                conditionSql = " from upcase." + tableName;
                whereSql = "org_code=" + "'" + orgCode + "' and is_deleted='0' and  (dept_code is null or dept_code='')";
                sqlStr = "select " + fieldSql + conditionSql + " where " + whereSql + " limit 1";
                dataMap = cSourceDocCommonOperateMapper.getDataMap(sqlStr);
            }
            //组装参数值表
            if (ObjectUtil.isNotEmpty(dataMap)) {
                for (String field : fieldList) {
                    String value=  dataMap.get(field) == null ? "" : dataMap.get(field).toString();
//                    value= DateUtil.formatDateStr(value);
                    sourceDataMap.put(tableName + "." + field, dataMap.get(field) == null ? "" : dataMap.get(field).toString());
                }
            }
        }
        return sourceDataMap;
    }

    /**
     * 从文书管理 获取模板详情
     *
     * @param documentCatalogCode 文件目录的代码
     * @return {@link Map<String, Object> }
     * @author shishengyao
     * @date 2022/02/26
     */
    public Map<String, Object> getTemplateDetail(String documentCatalogCode, String caseSourceId,String templateType) {
        //根据文书目录编码获取模板code
        String templateCode = getTemplateCodeByDocumentCatalogCode(documentCatalogCode, caseSourceId,null);

        Map<String, String> headers = HeaderUtil.headerInfo();

        Map<String, Object> paramsMap = new HashMap<>();
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("templateCode", templateCode);
        requestMap.put("templateType", templateType);
        String result = HttpUtil.createPost(url.concat(templateDetail)).addHeaders(headers).body(JSON.toJSONString(requestMap)).contentType("application/json").execute().body();
        if (StringUtils.isNotBlank(result)) {
            JSONObject jsonObject = JSONObject.parseObject(result);
            if ("200".equals(jsonObject.get("code").toString())) {

                if (ObjectUtil.isEmpty(jsonObject.get("data"))){
                    throw new BusinessException(templateCode+"对应的文书不存在");
                }
                JSONObject data = JSON.parseObject(jsonObject.get("data").toString());
                //获取返回的html内容
                paramsMap.put("htmlContent", data.getString("standardFormTemplate"));
                paramsMap.put("templateFieldConfigs", data.getString("templateFieldConfigs"));
                paramsMap.put("sourceFieldInfos", data.getString("sourceFieldInfoMap"));

            } else {
                log.info("调用文书服务失败，result:" + result);
            }
        }else {
            log.info("调用文书服务失败，result:" + result);
            throw new BusinessException(templateCode+"对应的文书不存在");
        }
        return paramsMap;
    }

    /**
     * 获取转换生成pdf并上传到oss的地址
     *
     * @param pdfRequest pdf格式的请求
     * @return {@link String }
     * @author shishengyao
     * @date 2022/02/25
     */
    public Map<String, String> getConvertedPdfUrl(FillAndConvertToPdfRequest pdfRequest) {

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("templateCode", pdfRequest.getTemplateCode());
        paramMap.put("paramMap", pdfRequest.getParamMap());
        paramMap.put("templateType", pdfRequest.getTemplateType());
        String result = HttpClientUtil.executeRequest(url + uploadConvertedPdf, "POST", "application/json", paramMap);
        if (StringUtils.isNotBlank(result)) {
            JSONObject jsonObject = JSONObject.parseObject(result);
            if ("200".equals(jsonObject.get("code").toString())) {
                String dataResult = jsonObject.get("data").toString();
                JSONObject data = JSON.parseObject(dataResult);
                Map<String, String> resultMap = new HashMap<>();
                //文书地址
                resultMap.put("fileUrl", data.getString("fileUrl"));
                //生成文书base64
                resultMap.put("fileBase64", data.getString("fileBase64"));
                return resultMap;
            } else {
                throw new BusinessException(jsonObject.getString("message"));
            }
        } else {
            throw new BusinessException("文书生成服务网络异常");
        }
    }

    /**
     * 文件签章并上传到oss
     *
     * @param queryDto 查询dto
     * @return {@link Map<String, String> }
     * @author shishengyao
     * @date 2022/03/07
     */
    @Override
    public String dealFileSeal(FileSealInfoQueryDto queryDto) {
        queryDto.setFileType("pdf");
        queryDto.setFileTransferForm("1");
        queryDto.setFileBase64(queryDto.getFileBase64());
        queryDto.setAddSignTime(false);
        queryDto.setSealCode("");
        queryDto.setKey("签章处");
        queryDto.setSignType(4);
        queryDto.setSealCode("12");
        queryDto.setPosX(0);
        queryDto.setPosY(0);
        //签章
        Map<String, Object> fileAfterSeal = fileSealProvinceUnifiedService.getFileAfterSeal(queryDto);
        if (ObjectUtil.isNotEmpty(fileAfterSeal.get("errorMsg"))) {
            log.info("warn fileSealService,result:{}", fileAfterSeal.get("errorMsg"));
            throw new BusinessException(fileAfterSeal.get("errorMsg").toString());
        }
        //获取pdf页码若2张以上，加盖骑缝章
        try {
            byte[] fileBytes = (byte[]) fileAfterSeal.get("fileBytes");
            InputStream ins = new ByteArrayInputStream(fileBytes);
            PdfReader pdfReader = new PdfReader(ins);
            int pages = pdfReader.getNumberOfPages();
            if (pages > 1) {
                queryDto.setFileType("pdf");
                queryDto.setFileTransferForm("1");
                String base64 = Base64.encodeBase64String(fileBytes);
                queryDto.setFileBase64(base64);
                queryDto.setKey("");
                queryDto.setSealCode("21");
                queryDto.setSignType(3);
                queryDto.setPosX(100);
                queryDto.setPosY(450);
                queryDto.setPosPage("1-" + pages);
                fileAfterSeal = fileSealProvinceUnifiedService.getFileAfterSeal(queryDto);
                if (ObjectUtil.isNotEmpty(fileAfterSeal.get("errorMsg"))) {
                    log.info("warn fileSealService,result:{}", fileAfterSeal.get("errorMsg"));
                    throw new BusinessException(fileAfterSeal.get("errorMsg").toString());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException("系统异常:" + e.getMessage());
        }

        //上传签章后的文件到oss
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("fileBytes", fileAfterSeal.get("fileBytes"));
        jsonObject.put("fileType", "pdf");
        jsonObject.put("fileName", "");
        JSONObject parseObject = JSON.parseObject(HttpUtil.post(url + uploadBase64File, jsonObject.toString()));
        String cd = "code";
        int th = 200;
        if (parseObject.getInteger(cd) == th) {
            String url = parseObject.getJSONObject("data").getString("ossUrl");
            log.info("签章后地址：{}", url);
            return url;
        } else {
            log.info("warn receive sign file upload oss fail,result:{}", parseObject.toString());
            throw new BusinessException("签章后上传文件失败：" + jsonObject.getString("message"));
        }

    }

    /**
     * 描述：处理文书模板填充参数
     *
     * @param saveDto 保存dto
     * @return {@link Map<String, Object> }
     * @author shishengyao
     * @date 2022/03/10
     */
    private Map<String, Object> dealDocParamMap(CSourceDocCommonOperateSaveDto saveDto) {
        // 送达地址确认书校验参数
        if (DocumentKindEnum.DOC_KIND_SDDZQRS.getCode().equals(saveDto.getDocumentKindCode())) {
            HashMap<String, Object> dataMap = saveDto.getDataMap();
            if (ObjectUtil.isNotEmpty(dataMap.get("SDDZQRS_SJHM"))) {
                if (!BaseUtil.validatePhoneNumber(dataMap.get("SDDZQRS_SJHM").toString())) {
                    throw new BusinessException("送达地址确认书手机号不正确");
                }
            }
        }
        Map<String, Object> paramMap = saveDto.getDataMap();
        if (ObjectUtil.isEmpty(paramMap.get(Constant.DOC_MAIN_HANDLE_SIGN_PIC)) ||
                ObjectUtil.isEmpty(Constant.DOC_ASSIST_HANDLE_SIGN_PIC)) {
        Map<String, Object> templateDetail = getTemplateDetail(saveDto.getDocumentCatalogCode(), saveDto.getCaseSourceId(),DocumentTemplateTypeEnum.getMappingCodeByCode(saveDto.getDocumentTemplateType()));
        //循环给自动填充的字段赋值
        Map templateFieldConfigs = JSON.parseObject(templateDetail.get("templateFieldConfigs").toString());
        //主办人、承办人签名
         String mainHandleSignPic =Constant.DOC_MAIN_HANDLE_SIGN_PIC;
         String assistHandleSignPic =Constant.DOC_ASSIST_HANDLE_SIGN_PIC;
        if (ObjectUtil.isNotEmpty(templateFieldConfigs.get(mainHandleSignPic)) ||
                ObjectUtil.isNotEmpty(templateFieldConfigs.get(assistHandleSignPic))) {
            List<CaseSourceHandlePersonRecord> personList = caseSourceHandlePersonRecordService.getCaseSourceHandlePersonRecordList(saveDto.getCaseSourceId());
            personList.forEach(e -> {
                if (HandlePersonTypeEnum.MAIN.getCode().equals(e.getHandlePersonType()) && ObjectUtil.isNotEmpty(templateFieldConfigs.get(mainHandleSignPic))) {
                    paramMap.put(mainHandleSignPic, e.getHandleSignPic());
                } else if (HandlePersonTypeEnum.ASSIST.getCode().equals(e.getHandlePersonType()) &&  ObjectUtil.isNotEmpty(templateFieldConfigs.get(assistHandleSignPic))) {
                    paramMap.put(assistHandleSignPic, e.getHandleSignPic());
                }
            });
        }}
        return paramMap;
    }

    /**
     * 描述：【V1.0.0】文书文号生成
     *
     * @author tianrunjia
     * @date 2022-02-23
     */
    @Override
    public String getDocumentNumber(String caseSourceId, String documentCatalogCode) {
        //“X机构”处填写制作法律文书的办案单位文号； X机构（ ）字〔 〕第 号
        //双执法主体切换
        /*List<CaseHandlePersonRecordVo> caseHandlePersonRecordVoList = caseHandlePersonRecordService.getCaseHandlePersonRecordListByCaseId(caseId);
        String handleDeptCode = caseHandlePersonRecordVoList.get(0).getHandleOrgCode();*/
        //String docDeptShort = configBusiParamDeptService.getConfigBusiParamDeptDetailByDeptCode(handleDeptCode).getDocumentDeptShort();
        //CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        CaseSourceRegisterMainInfo caseSourceRegisterMainInfo=caseSourceRegisterMainInfoMapper.selectByPrimaryKey(caseSourceId);
        /*SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCode(caseSourceRegisterMainInfo.getHandleOrgCode());
        String docDeptShort = sysDepartParam.getOrgShortName();*/
        String orgCode=caseSourceRegisterMainInfo.getHandleOrgCode();
        String deptCode=caseSourceRegisterMainInfo.getHandleDeptCode();
        if (ObjectUtil.isEmpty(orgCode)){
            orgCode=caseSourceRegisterMainInfo.getCreateUserOrgCode();
            deptCode=caseSourceRegisterMainInfo.getCreateUserDeptCode();
        }
        // 获取条线信息
        LineTerritoryInfoVo lineTerritoryInfoVo = sysDepartParamService.getLineInfoByOrgCodeAndLineCode(orgCode,deptCode, caseSourceRegisterMainInfo.getLineCode());
        String lineDocNumber = lineTerritoryInfoVo.getLineDocNumber();
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
        //获取（ ）内的内容 如立案、移案、询通、调证、登保决、鉴聘、申避决、听通、当罚决、不罚决、行罚决、行罚缴决、强执决、代履决、强执申、电送确、终决等；
        String numAbbreviation = configBusiParamDocumentInfo.getDocumentNumberAbbreviation();
        //获取年度 “〔 〕”处填写年度
        String curretYear = "〔" + String.valueOf(LocalDate.now().getYear()) + "〕";
        //String curretYear = "〔1990〕";
        //“第 号”处填写4位自增序号的顺序编号。从缓存原子中获取
        String documentNumberKey = "UPCASE-DOCUMENTNUMBERKEY-" + curretYear;
        // long number = redisRepository.incr(documentNumberKey);

        String lineCode = lineDocNumber;
        //案源文号改造
        String documentNumberSerialType = configBusiParamDocumentInfo.getDocumentNumberSerialType();
        if (Constant.STRING_4.equals(documentNumberSerialType)) {
            //4-与某文书使用相同序列
            documentCatalogCode = configBusiParamDocumentInfo.getDocumentNumberMatchCatalogCode();
            lineCode = lineTerritoryInfoVo.getLineCode();
        }

        long number = caseDocumentNumberSerialService.getNumber(caseSourceId, "CSOURCE", documentCatalogCode, orgCode, deptCode, lineCode, curretYear);
        //String documentNumber = docDeptShort + "（" + numAbbreviation + "）" + curretYear + String.format("%06d", number);
        String documentNumber = lineDocNumber + numAbbreviation + curretYear + "第" + String.format("%06d", number) + "号";
        if (TerritoryCodeEnum.STHJ.getCode().equals(lineTerritoryInfoVo.getTerritoryCode())) {
            //生态环境文号生成规则：生态环境全部文书，去掉文号里面的“第”，数字虚号“00000”
            documentNumber = lineDocNumber + numAbbreviation + curretYear + number + "号";
        }
        return documentNumber;
    }


    /*@Autowired
    public void setRedisRepository(RedisRepository redisRepository) {
        this.redisRepository = redisRepository;
    }*/




    /**
     * 描述：移送函移送
     *
     * @author shishengyao
     * @date 2022/05/25
     */
    public void dealSpecialDocument(StageDocCommonOperateSaveDto saveDto) {
        // todo 案源移送待处理
        if (DocumentKindEnum.DOC_KIND_DK2AYYSH.getCode().equals(saveDto.getDocumentKindCode())) {

        }
    }
}
